using System;

using Community.CsharpSqlite.SQLiteClient;

using log4net;

using VSTalk.Logger;

namespace VSTalk.Engine.Core.Data.Migration
{
    public class Migration2 : IMigrationScript
    {
        private static readonly ILog _log = LoggerFactory.Create(typeof(Migration1));
        private SqliteConnection _connection;

        public void Apply(SqliteConnection connection)
        {
            _connection = connection;
            _log.Info("Start updating db");
            _connection.Open();
            try
            {
                CreateVcard();
                SetupVersion();
            }
            catch (Exception e)
            {
                _log.Fatal("Unexpected error", e);
                throw;
            }
            finally
            {
                _connection.Close();
            }

        }

        private void CreateVcard()
        {
            string sql = @"
CREATE TABLE contact_details (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
jid varchar(2048) NOT NULL,
hash varchar(2048) NOT NULL,
fullname varchar(2048) NULL,
url varchar(2048) NULL,
birthday INTEGER NULL,
details TEXT NULL,
photoType varchar(2048) NULL,
photoBin BLOB NULL
);
CREATE INDEX IX_contact_details ON contact_details(jid, hash)
";
            var command = new SqliteCommand(sql, _connection);
            command.ExecuteNonQuery();
        }

        private void SetupVersion()
        {
            string sql = "update version set num = 3";
            var command = new SqliteCommand(sql, _connection);
            command.ExecuteNonQuery();
        }
    }
}